/**
 * Copyright (c) 2012 Nokia Corporation.
 */

package com.nokia.example.gfxsensorsdemo;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import com.nokia.example.gfxsensorsdemo.graphics.MyCanvas;

/**
 * Main class.
 */
public class Main extends MIDlet implements CommandListener {

	private Display display;
	private Command exit;
	
    static Main instance;
    Timer iTimer = new Timer();
    private Canvas _canvas = null;
    
    /**
     * Constructor.
     */
	public Main() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#startApp()
	 */
	protected void startApp() throws MIDletStateChangeException {
		this.exit = new Command("Exit", Command.EXIT, 0x01);
		
		_canvas = new MyCanvas();
		_canvas.setFullScreenMode(true);
		_canvas.setCommandListener(this);
		_canvas.addCommand(this.exit);
		
		this.display = Display.getDisplay(this);
		display.setCurrent(_canvas);
		
        iTimer.schedule(new MyTimerTask(), 0, 40);		
	}

	/* (non-Javadoc)
	 * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)
	 */
	public void commandAction(Command command, Displayable displayable) {
		if (command == this.exit) {
			try {
				this.destroyApp(true);
			} catch (MIDletStateChangeException e) {
				e.printStackTrace();
			} finally {				
				this.notifyDestroyed();
			}
		}
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#destroyApp(boolean)
	 */
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
	
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#pauseApp()
	 */
	protected void pauseApp() {}
    
    /**
     * Quit the MIDlet.
     */
    public static void quitApp() {
        try {
			instance.destroyApp(true);
		} catch (MIDletStateChangeException e) {
			e.printStackTrace();
		}
        
        instance.notifyDestroyed();
        instance = null;
    }

    /**
     * Timer task for providing animation.
     */
    class MyTimerTask extends TimerTask {
    	public void run() {
            if(_canvas != null) {
            	_canvas.repaint();
            }
        }
    }	
}
